import React, { useCallback, useEffect } from 'react';
import { connect, history } from 'umi';
import { Button, Card, message } from 'antd';
import { useGrid } from '@/utils/hooks';
import { Title } from '@/components/common';
import { xbomModule as authModuleName, AuthActions, auth } from '@/utils/auth';
import { stateEnum } from '@/pages/xbommanage/SpecialOrder/page/XbomObjectCreate/util';
import { getContentHeight } from '@/utils/utils';
import { XBomEffects, namespace } from './types';
import type { PageProps, DvaState, DispatchProps } from './types';
import { UiSchema, XBomSearchSchema } from './Schema';
import XbomDetailModal from './solt/XbomObjectDetail';
import TransferPerson from './solt/TransferPerson';
import SearchTable from './solt/SearchTable';
import RecipientListModal from './solt/RecipientListModal';
import DefaultPeopleSetListModal from './solt/DefaultPeopleSetListModal';
import { transferFormValues, staticChangeRow, checkIsAdmin } from './utils';

const { SearchSchema } = XBomSearchSchema;

function HeaderRight({ enigineStateProps, gridManagerRef }) {
  const { reveiceOrderLoading, ...dispatchToProps } = enigineStateProps;
  const {
    selectedRows, // 列表选中的行
  } = enigineStateProps[namespace];
  const {
    receiveOrderEffect,
    save, // 保存全局数据
    queryXbom,
  } = dispatchToProps;
  const hasReceived = +selectedRows[0]?.state !== stateEnum.notReceived; // 未接收的都为已接收
  const isCanReceivedOrder = !!selectedRows.length && !hasReceived; // 是否可以接收订单
  const isCanCreatXbom = !!selectedRows.length && hasReceived; // 是否可以进行xbom维护

  // 接收订单请求
  const receiveOrder = useCallback(async () => {
    await receiveOrderEffect();
    staticChangeRow({
      gridManagerRef,
      selectedRows,
      changeObj: { state: '2' },
    });
  }, [gridManagerRef, receiveOrderEffect, selectedRows]);

  // 查询xbom对象详情弹窗
  const openXbomDetailModal = useCallback(() => {
    save({
      xbomDetailVisible: true,
    });
    queryXbom();
  }, [queryXbom, save]);

  return (
    <>
      <Button
        size="small"
        onClick={() => {
          save({
            recipientListVisible: true,
          });
        }}
      >
        {'设置常用收件人'}
      </Button>
      <Button
        size="small"
        onClick={() => {
          if (!checkIsAdmin()) {
            // 当前登陆人是否有权限操作
            message.error('仅限管理员操作');
            return;
          }
          save({
            defaultPeopleSetListVisible: true,
          });
        }}
      >
        设置默认负责人
      </Button>

      {/*接收订单*/}
      {auth(authModuleName, AuthActions.receiveOrders) && (
        <Button size="small" disabled={!isCanReceivedOrder} loading={reveiceOrderLoading} onClick={receiveOrder}>
          接收订单
        </Button>
      )}

      {/* 设置MBOM工程师 */}
      {auth(authModuleName, AuthActions.setupMbom) && (
        <TransferPerson selectedRows={selectedRows} gridManagerRef={gridManagerRef} type="setmbom" multiple />
      )}

      {/* 转移责任人 */}
      {auth(authModuleName, AuthActions.transferOwner) && (
        <TransferPerson selectedRows={selectedRows} gridManagerRef={gridManagerRef} type="responsible" />
      )}

      {/* 转移接口人 */}
      {auth(authModuleName, AuthActions.transferInterfacePerson) && (
        <TransferPerson selectedRows={selectedRows} gridManagerRef={gridManagerRef} type="interface" />
      )}

      {/* 设置协助人人 */}
      {auth(authModuleName, AuthActions.setupAassistant) && (
        <TransferPerson selectedRows={selectedRows} gridManagerRef={gridManagerRef} type="assist" multiple />
      )}
      {auth(authModuleName, AuthActions.xbomMaintain) && (
        <Button
          size="small"
          disabled={!isCanCreatXbom}
          onClick={() => {
            let basepathname = `/xbom/xbomMaintenance/detail/${selectedRows[0].id}`;
            if (selectedRows[0].xbomId) {
              basepathname += `/${selectedRows[0].xbomId}`;
            }
            history.push({
              pathname: basepathname,
              query: { forceRender: true },
            });
            // 清空勾选，防止selectedRows缓存导致的bug
            save({
              selectedRows: [],
            });
          }}
        >
          {'Xbom对象维护'}
        </Button>
      )}
      {auth(authModuleName, AuthActions.xbomObjectDetail) && (
        <Button size="small" disabled={!isCanCreatXbom} onClick={openXbomDetailModal}>
          {'Xbom对象详情'}
        </Button>
      )}
    </>
  );
}

function Page(enigineStateProps: PageProps) {
  const { userId, gridLoading, MAIN_CONFIG, ...dispatchToProps } = enigineStateProps;
  const gridHeight = getContentHeight(MAIN_CONFIG, 120);
  const {
    list, // 列表数据
    searchParams, // 列表原始查询参数 -- 分页?
    selectedRows, // 列表选中的行
    xbomDetailVisible, // xbom详情弹窗展示
    xbomData, // xbom对象
    recipientListVisible,
    defaultPeopleSetListVisible,
  } = enigineStateProps[namespace];
  const {
    query,
    save, // 保存全局数据
  } = dispatchToProps;

  const { onGridReady, gridManagerRef } = useGrid({}); // gridManagerRef - 列表操作对象, onGridReady - 列表准备完成

  useEffect(() => {
    query({});
  }, [query]);

  return (
    <>
      <Card size="small" bodyStyle={{ padding: '3px' }} title={<Title />}>
        <SearchTable
          gridOptions={{
            height: gridHeight,
            gridKey: 'xbommanage-SpecialOrder-SearchTable-smartGrid',
            gridLoading: gridLoading,
            headerProps: {
              type: 'line',
              extra: <HeaderRight enigineStateProps={enigineStateProps} gridManagerRef={gridManagerRef} />,
            },
            dataSource: list,
            rowSelection: {
              onSelect: (_: string[], selectedRows: typeof list) => {
                save({
                  selectedRows,
                });
              },
              selectedRows,
              type: 'single', // 控制单选
            },
            onReady: onGridReady,
          }} // 表格配置
          smartSearchOptions={{
            smartSearchKey: 'xbommanage-SpecialOrder-SearchTable-smartSearchKey',
            searchLoading: gridLoading,
            initParams: searchParams,
            onSearch: (filterInfo) => query(filterInfo),
            searchSchema: SearchSchema,
            uiSchema: UiSchema,
            userId,
            isCustomParams: true,
            onViewChange: (view: any) => save({ initSmartSearchView: view }), // 试图变化触发
          }} // 智能搜索配置
        />

        {/* XBOM详情弹窗 */}
        <XbomDetailModal
          value={{
            tableData: transferFormValues(selectedRows[0]),
            objectData: {
              ...xbomData,
              requirementDesc: selectedRows[0]?.requirementDesc,
              basicPno18: selectedRows[0]?.basicPno18,
              effectiveTimeStr: xbomData?.effectiveTime,
            },
          }} // xbom默认传入的表单数据
          onCancel={() => {
            save({
              xbomDetailVisible: false,
            });
          }}
          visible={xbomDetailVisible}
        />

        {/*设置常用收件人弹窗 */}
        <RecipientListModal
          onCancel={() => {
            save({
              recipientListVisible: false,
            });
          }}
          visible={recipientListVisible}
        />

        {/*设置默认负责人弹窗 */}
        <DefaultPeopleSetListModal
          onCancel={() => {
            save({
              defaultPeopleSetListVisible: false,
            });
          }}
          visible={defaultPeopleSetListVisible}
        />
      </Card>
    </>
  );
}

export default connect(
  (dvaStore: DvaState) => {
    const { loading, user, settings } = dvaStore;
    return {
      [namespace]: dvaStore[namespace],
      gridLoading: loading.effects[XBomEffects.query],
      createXbomLoading: loading.effects[XBomEffects.createXbom],
      reveiceOrderLoading: loading.effects[XBomEffects.receiveOrderEffect], // 接收特改订单加载状态
      userId: user.currentUser.id,
      MAIN_CONFIG: settings.MAIN_CONFIG,
    };
  },
  (dispatch: DispatchProps) => {
    return Object.entries(XBomEffects)
      .map(([key, value]) => {
        return {
          [key]: (payload: any) => dispatch({ type: value, payload }),
        };
      })
      .reduce((acc, obj) => Object.assign(acc, obj), {});
  },
)(Page);
